package main

import (
	"net/http"
)

var m *router

func init() {
	m = &router{}
	m.r = make(map[string]func(http.ResponseWriter, *http.Request))
}

type router struct {
	r map[string]func(http.ResponseWriter, *http.Request)
}

func (this *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	for k, fun := range this.r {
		if k == r.RequestURI {
			fun(w, r)
			return
		}
	}
	w.Write([]byte("404"))
}

func (this *router) AddRouter(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) {
	this.r[pattern] = handlerFunc  // 将 func(http.ResponseWriter, *http.Request) 类型 转换 http.HandlerFunc 类型。 http.HandlerFunc 实现了 ServeHTTP的方法（实际就是调用自己）
}

func updateOne(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello"))
}

func update(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello2"))
}

func main() {
	m.AddRouter("/update_one", updateOne)
	m.AddRouter("/update", update)

	http.ListenAndServe(":8888", m)  // 一单访问了域名便会 访问 m 的 ServeHTTP 方法

}